﻿using ActionSystem.Core;
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace XMLib.AM
{
    /// <summary>
    /// GroupListView:状态组，方便查看
    /// </summary>
    [Serializable]
    public class StateGroupListView : IDataView
    {
        public override string title => "状态组列表";
        public override bool useAre => true;
        private Vector2 scrollPos;

        

        public override void OnUpdate()
        {
            
        }
        protected override void OnGUI(Rect contentRect)
        {
            List<StateGroup> states = win.currentStateGroups;
            if (null == states)
            {
                return;
            }

            EditorGUI.BeginChangeCheck();
            //绘制list
            win.stateGroupSelectIndex = EditorGUILayoutEx.DrawList(states, win.stateGroupSelectIndex, ref scrollPos, NewGroup, StateGroupDrawer);
        }
        private void NewGroup(Action<StateGroup> adder)
        {
            var newGroup = new StateGroup();
            int maxGroupIndex = GetMaxUID();
            newGroup.GID = (maxGroupIndex + 1);
            adder(newGroup);
        }

        private int GetMaxUID()
        {
            int maxGroupIndex = -1;
            if (win.currentStateGroups != null)
            {
                for (int i = 0; i < win.currentStateGroups.Count; i++)
                {
                    if (maxGroupIndex < win.currentStateGroups[i].GID)
                    {
                        maxGroupIndex = win.currentStateGroups[i].GID;
                    }
                }
            }

            return maxGroupIndex;
        }
        public void StateGroupDrawer<T>(int index, ref bool selected, T obj) where T : StateGroup
        {
            if(obj.GID == StateGroup.NoGroup)
            {
                obj.GID = GetMaxUID() + 1;
            }
            if (GUILayout.Button($"{index}", selected ? AEStyles.item_head_select : AEStyles.item_head_normal, GUILayout.ExpandHeight(true), GUILayout.Width(15)))
            {
                GUI.FocusControl(null);
                selected = !selected;
            }
            if (GUILayout.Button($"{obj?.GroupName}", selected ? AEStyles.item_body_select : AEStyles.item_body_normal, GUILayout.Height(30f), GUILayout.ExpandWidth(true)))
            {
                GUI.FocusControl(null);
                selected = !selected;
            }
        }
        public override object CopyData()
        {
            return win.currentStateGroup;
        }
        public override void PasteData(object data)
        {
            if (win.currentStateGroups != null&&data is StateGroup group)
            {
                group.GID = GetMaxUID() + 1;
                win.currentStateGroups.Add(group);
                win.stateGroupSelectIndex = win.currentStateGroupCount - 1;
            }
        }

        
    }
}
